<!DOCTYPE html>
<html>

<head>
</head>

<body>
    <div>
        <input type="file" id="file-1" class="inputfile" onchange="change()" />
        <div>
            <span id="startPre">
                <a id="startLink" onclick="recognizeText()" href="#log">Click here to recognize text</a> or choose your
                own
                image
            </span>
        </div>
        <img id="image-img"></img>
        <canvas id="image-rec"></canvas>
        <div id="log">
        </div>
    </div>
    <script>
        async function recognizeText() {
            var file = document.getElementById('file-1').files[0];
            if (!file) {
                return;
            }
            // 模型初始化
            var ocr = window.paddlejs.ocr;
            await ocr.init('./models/ocr_v2_det_new/model.json',
                './models/ocr_v2_rec_320/model.json');

            // 获取文本识别结果API，img为用户上传图片，option为可选参数
            // option.canvas as HTMLElementCanvas：若用户需要绘制文本框选区域，传入canvas元素
            // option.style as object：若用户需要配置canvas 样式，传入style 对象
            // option.style.strokeStyle as string：文本框选颜色
            // option.style.lineWidth as number：文本框选线段宽度
            // option.style.fillStyle as string：文本框选填充颜色
            var img = document.getElementById('image-img');
            var canvas = document.getElementById('image-rec');

            const res = await ocr.recognize(img, { 'canvas': canvas });
            // 识别文字结果
            console.log(res.text);
            traggleImageRec(true);

            var log = document.getElementById('log');
            log.innerHTML = '';
            if (res.text && res.text.length) {
                for (var i = 0; i < res.text.length; i++) {
                    var pre = document.createElement('pre');
                    pre.innerText = res.text[i];
                    log.append(pre);
                }
            }
        }

        function change() {
            var file = document.getElementById('file-1').files[0];
            if (!file) {
                return;
            }
            traggleImageRec(false);
            var img = document.getElementById('image-img');
            img.src = window.URL.createObjectURL(file)

        }

        function traggleImageRec(show) {
            var canvas = document.getElementById('image-rec');
            if (show) {
                canvas.style.display = 'block';
            } else {
                canvas.style.display = 'none';
            }
        }


    </script>
</body>

<script src='./ocr.js'></script>

</html>